//
//  AppDelegate.m
//  MUBATE
//
//  Created by sunbin on 2017/2/13.
//  Copyright © 2017年 Quanli. All rights reserved.
//

#import "AppDelegate.h"
#import "FinancialReport.h"
#import "NavigationController.h"

#import "Login.h"
#import "UserQrCode.h"

#import "NewMessageTool.h"

#import "AppDelegateConfig.h"
#import "NavigationController.h"
#import "TopWindow.h"

@interface AppDelegate ()<WeiboSDKDelegate ,WXApiDelegate ,JPUSHRegisterDelegate>
@end
@implementation AppDelegate
{
    BQLDBTool *tool;
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    

    // 项目配置
    tool =  [[AppDelegateConfig sharedAppDelegateConfig] notiApplication:application didFinishLaunchingWithOptions:launchOptions appDelegate:self];
    
    
    
    [self insertedIntoDatabase:@{@"data":@{@"add_time":@"2017.01.21" ,@"money":@"30221" ,@"record_id":@"4" ,@"type":@"1"}}];
    _userInfo = [YConfig myProfile];

    _window.rootViewController = [self getRootViewController];
    [_window makeKeyAndVisible];

    return YES;
}

// 懒加载 UIWindow
- (UIWindow *)window
{
    if (!_window) {
        _window                 = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
        _window.backgroundColor = [UIColor whiteColor];
        [_window makeKeyAndVisible];
    }
    return _window;
}

// 懒加载 RootViewController
-(RootViewController *)rootViewController{
    if (!_rootViewController) {
        _rootViewController = [[RootViewController alloc] initWithNibName:@"RootViewController" bundle:nil];
    }
    return _rootViewController;
}

// 根视图控制器
- (UIViewController *)getRootViewController{
    if ([YConfig getOwnID] != 0) {
        // 开启远程通知
        [[UIApplication sharedApplication] registerForRemoteNotifications];
        NavigationController *navigationController = _rootViewController?[[NavigationController alloc] initWithRootViewController:_rootViewController]:[[NavigationController alloc] initWithRootViewController:[self rootViewController]];
        
        return  navigationController;
    }else{
        [[UIApplication sharedApplication] unregisterForRemoteNotifications];

        Login *launch = [[Login alloc] init];
        return launch;
    }}


// setUserInfo
-(void)setUserInfo:(YUserInfo *)userInfo
{
    [YConfig saveProfile:userInfo];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"SET_USERINFO" object:nil];
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    [application setApplicationIconBadgeNumber:0];
    [application cancelAllLocalNotifications];
}



- (void)applicationDidBecomeActive:(UIApplication *)application {
    // 给状态栏添加一个按钮可以进行点击, 可以让屏幕上的scrollView滚到最顶部
    [TopWindow show];
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


// .handle open url
- (BOOL)application:(UIApplication *)application openURL:(nonnull NSURL *)url options:(nonnull NSDictionary<NSString *,id> *)options {
    // 这里建议判断下
    return [WeiboSDK handleOpenURL:url delegate:self];
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    [WeiboSDK handleOpenURL:url delegate:self ];
    [WXApi handleOpenURL:url delegate:[WXApiManager sharedManager]];

    return  YES;
}
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    [WeiboSDK handleOpenURL:url delegate:self];
    [WXApi handleOpenURL:url delegate:[WXApiManager sharedManager]];
    
    return  YES;
}



#pragma mark -- WeiboSDKDelegate
- (void)didReceiveWeiboRequest:(WBBaseRequest *)request {
}
- (void)didReceiveWeiboResponse:(WBBaseResponse *)response {

    
}

- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    NSLog(@"%@", [NSString stringWithFormat:@"Device Token: %@", deviceToken]);
    [JPUSHService registerDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)application
didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}

#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_7_1
- (void)application:(UIApplication *)application
didRegisterUserNotificationSettings:
(UIUserNotificationSettings *)notificationSettings {
}

// Called when your app has been activated by the user selecting an action from
// a local notification.
// A nil action identifier indicates the default action.
// You should call the completion handler as soon as you've finished handling
// the action.
- (void)application:(UIApplication *)application
handleActionWithIdentifier:(NSString *)identifier
forLocalNotification:(UILocalNotification *)notification
  completionHandler:(void (^)())completionHandler {
}

// Called when your app has been activated by the user selecting an action from
// a remote notification.
// A nil action identifier indicates the default action.
// You should call the completion handler as soon as you've finished handling
// the action.
- (void)application:(UIApplication *)application
handleActionWithIdentifier:(NSString *)identifier
forRemoteNotification:(NSDictionary *)userInfo
  completionHandler:(void (^)())completionHandler {
}
#endif

- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo {
    [JPUSHService handleRemoteNotification:userInfo];
    NSLog(@"iOS6及以下系统，收到通知:%@", [self logDic:userInfo]);
    [_rootViewController addNotificationCount];
}

- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:
(void (^)(UIBackgroundFetchResult))completionHandler {
    [JPUSHService handleRemoteNotification:userInfo];
    NSLog(@"iOS7及以上系统，收到通知:%@", [self logDic:userInfo]);
    
    if ([[UIDevice currentDevice].systemVersion floatValue]<10.0 || application.applicationState>0) {
        [_rootViewController addNotificationCount];
    }
    
    completionHandler(UIBackgroundFetchResultNewData);
}


- (void)application:(UIApplication *)application
didReceiveLocalNotification:(UILocalNotification *)notification {
    [JPUSHService showLocalNotificationAtFront:notification identifierKey:nil];
}

#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#pragma mark- JPUSHRegisterDelegate
// 前台接收消息 接收到消息
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    NSDictionary * userInfo = notification.request.content.userInfo;
    

    NSString *share_id =IF_NULL_TO_STRING([userInfo objectForKey:@"share_id"]);
    if (![NHUtils isBlankString:share_id]) {
        //类型 type=1交易 2共享返现
        NSString *type = IF_NULL_TO_STRING([userInfo objectForKey:@"type"]);
        
#warning 模拟数据
        [NewMessageTool newMessageTool:tool insertData:@"3" money:@"12456" type:type add_time:@"2017.03.05 18:09" isRead:@"1" issuccessful:@"1"];
    }
    
    UNNotificationRequest *request = notification.request; // 收到推送的请求
    UNNotificationContent *content = request.content; // 收到推送的消息内容
    
    NSNumber *badge = content.badge;  // 推送消息的角标
    NSString *body = content.body;    // 推送消息体
    UNNotificationSound *sound = content.sound;  // 推送消息的声音
    NSString *subtitle = content.subtitle;  // 推送消息的副标题
    NSString *title = content.title;  // 推送消息的标题
    
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        NSLog(@"iOS10 前台收到远程通知:%@", [self logDic:userInfo]);
        
        [_rootViewController addNotificationCount];
        
    }
    else {
        // 判断为本地通知
        NSLog(@"iOS10 前台收到本地通知:{\nbody:%@，\ntitle:%@,\nsubtitle:%@,\nbadge：%@，\nsound：%@，\nuserInfo：%@\n}",body,title,subtitle,badge,sound,userInfo);
    }
    completionHandler(UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionSound|UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以设置
}


//前台后台消息点击进入
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    UNNotificationRequest *request = response.notification.request; // 收到推送的请求
    UNNotificationContent *content = request.content; // 收到推送的消息内容
    
    NSNumber *badge = content.badge;  // 推送消息的角标
    NSString *body = content.body;    // 推送消息体
    UNNotificationSound *sound = content.sound;  // 推送消息的声音
    NSString *subtitle = content.subtitle;  // 推送消息的副标题
    NSString *title = content.title;  // 推送消息的标题
    
    [self goToMssageViewControllerWith:userInfo];

    
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        NSLog(@"iOS10 收到远程通知:%@", [self logDic:userInfo]);
        [_rootViewController addNotificationCount];
        
    }
    else {
        // 判断为本地通知
        NSLog(@"iOS10 收到本地通知:{\nbody:%@，\ntitle:%@,\nsubtitle:%@,\nbadge：%@，\nsound：%@，\nuserInfo：%@\n}",body,title,subtitle,badge,sound,userInfo);
    }
    
    completionHandler();  // 系统要求执行这个方法
}
#endif

// log NSSet with UTF8
// if not ,log will be \Uxxx
- (NSString *)logDic:(NSDictionary *)dic {
    if (![dic count]) {
        return nil;
    }
    NSString *tempStr1 =
    [[dic description] stringByReplacingOccurrencesOfString:@"\\u"
                                                 withString:@"\\U"];
    NSString *tempStr2 =
    [tempStr1 stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
    NSString *tempStr3 =
    [[@"\"" stringByAppendingString:tempStr2] stringByAppendingString:@"\""];
    NSData *tempData = [tempStr3 dataUsingEncoding:NSUTF8StringEncoding];
    NSString *str =
    [NSPropertyListSerialization propertyListFromData:tempData
                                     mutabilityOption:NSPropertyListImmutable
                                               format:NULL
                                     errorDescription:NULL];
    return str;
}




#pragma make 数据库操作
// 插入数据库
- (void)insertedIntoDatabase:(NSDictionary *)userInfo{
    NSDictionary *data = [userInfo objectForKey:@"data"];
    
    NSString *add_time = IF_NULL_TO_STRING([data objectForKey:@"add_time"]);
    NSString *money = IF_NULL_TO_STRING([data objectForKey:@"money"]);
    NSString *record_id = IF_NULL_TO_STRING([data objectForKey:@"record_id"]);
    //类型 type=1交易 2共享返现
    NSString *type = IF_NULL_TO_STRING([data objectForKey:@"type"]);
    
    NSString *status;//0代表失败 1代表成功
    status = [NSString stringWithFormat:@"%@" ,@"1"];

    [NewMessageTool newMessageTool:tool insertData:record_id money:money type:type add_time:add_time isRead:@"1" issuccessful:status];
}
#pragma mkae -信息入口
- (void)goToMssageViewControllerWith:(NSDictionary*)msgDic{
    NSDictionary *data = [msgDic objectForKey:@"data"];
    NSString *record_id = IF_NULL_TO_STRING([data objectForKey:@"record_id"]);
    NSString *type = IF_NULL_TO_STRING([data objectForKey:@"type"]);

}




@end
